package com.starbaba.messageManager.view;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.messageManager.model.PhoneMessageStatistical;
import com.starbaba.model.dictionary.Constant;

public class PhoneMessageStatisticalAction extends BaseAction {
	
	private static final long serialVersionUID = 4203299739986720669L;

	private static Map<Integer,String> channelMap = new HashMap<Integer, String>();
	
	private InputStream input;

	private String fileName;
	
	public InputStream getInput() {
		return input;
	}

	public void setInput(InputStream input) {
		this.input = input;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	
	
	static {
//		channelMap.put(1, "IXuanwu");
//		channelMap.put(2, "IChuangZhuo");
		channelMap.put(3, "昊博");
//		channelMap.put(4, "IYimei");
//		channelMap.put(5, "IMoveK");
		channelMap.put(6, "梦网");
		channelMap.put(8, "创蓝");
	}
	
	
	public String showPage() throws AppException {
		
		BaseDao baseDao = new BaseDao(Constant.POOL_LIFE);
		PhoneMessageStatistical channelModel = null;
		List<PhoneMessageStatistical> listChannel = new ArrayList<PhoneMessageStatistical>();
		for (Map.Entry<Integer, String> entry : channelMap.entrySet() ) {
			channelModel = new PhoneMessageStatistical();
			channelModel.setChannel(entry.getKey());
			channelModel.setChannel_name(entry.getValue());
			listChannel.add(channelModel);
		}
		paramsMap.put("listChannel", listChannel);
		
		String sql = "select DISTINCT prdid as product_id, name as product_name from comm_product_prdid";
		List<PhoneMessageStatistical> productList = baseDao.list(sql, PhoneMessageStatistical.class);
		paramsMap.put("productList", productList);
		return Action.SUCCESS;
	}
	
	
	public void queryInfo() {
		
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(
				Struts2Utils.getRequest(), paramsMap); // 将请求参数封装带paramsMap中
		String startTime = (String) paramsMap.get("startTime");
		String endTime = (String) paramsMap.get("endTime");
		String product_id = (String) paramsMap.get("product_id"); //产品id
		String channel = (String) paramsMap.get("channel"); //短信服务商id
		try {
			parsePageRequest();
			int pageSize = pageRequest.getIDisplayLength();
			int pageIndex = pageRequest.getIDisplayStart();

			PageResponse pageResponse = new PageResponse();
			BaseDao baseDao = new BaseDao(Constant.COMPANY_DB_POOL);
			
			StringBuilder stringBuilder = new StringBuilder(); 
			stringBuilder.append(" select id,totalCount,successCount,faildCount,channel,product_id,cdate FROM phone_message_statistical where 1 = 1 ");
			
			if(StringUtils.isNotEmpty(startTime)) {
				stringBuilder.append(" and cdate >= '"+startTime+"' ");
			}
			if(StringUtils.isNotEmpty(endTime)) {
				stringBuilder.append(" and cdate <= '"+endTime+"' ");
			}
			
			if(StringUtils.isNotEmpty(product_id)) {
				if("-1".equals(product_id)) {
					stringBuilder.append(" and product_id in (1,0,-1) "); //由于车主无忧产品 可能是-1或者1
				} else {
					stringBuilder.append(" and product_id = '"+Integer.valueOf(product_id)+"' ");
				}
			}
			
			if(StringUtils.isNotEmpty(channel)) {
				stringBuilder.append(" and channel = '"+Integer.valueOf(channel)+"' ");
			}
			
			stringBuilder.append(" order by cdate desc ");
			
			String limitSql = " limit " + pageIndex + "," + pageSize + " ";
			List dataList = baseDao.list(stringBuilder.toString() + limitSql, PhoneMessageStatistical.class);
		
			if(null != dataList && dataList.size() > 0) {
				for(int i = 0; i < dataList.size(); i++) {
					Object object = dataList.get(i);
					if(object instanceof PhoneMessageStatistical) {
						PhoneMessageStatistical vo = (PhoneMessageStatistical)object;
						vo.setChannel_name(channelMap.get(vo.getChannel()));
						Integer productId = vo.getProduct_id();
						System.out.println(productId);
						if(productId == 1) {
							vo.setProduct_name("车主无忧");
						} else {
							BaseDao relaseDao = new BaseDao(Constant.POOL_LIFE);
							String sql = "select DISTINCT name as product_name from comm_product_prdid where prdid = ? ";
							PhoneMessageStatistical tempVo = relaseDao.get(sql, PhoneMessageStatistical.class, productId);
							if (tempVo != null) {
								vo.setProduct_name(tempVo.getProduct_name());
							}
						}
					}
				}
			}
			
			pageResponse.setAaData(dataList);
			pageResponse.setSEcho(pageRequest.getSEcho());
			List tmpDataList = baseDao.list(stringBuilder.toString(), PhoneMessageStatistical.class);
			pageResponse.setITotalDisplayRecords(tmpDataList.size());
			pageResponse.setITotalRecords(tmpDataList.size());
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
			
		} catch (Exception e) {
			e.printStackTrace();
			LogService.error("getGeneraldata", e);
		}
	}
	
	
	
	public String exportCVS() throws Exception {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String startTime = (String) paramsMap.get("startTime");
		String endTime = (String) paramsMap.get("endTime");
		String product_id = (String) paramsMap.get("product_id"); //产品id
		String channel = (String) paramsMap.get("channel"); //短信服务商id
		BaseDao baseDao = new BaseDao(Constant.COMPANY_DB_POOL);
		String sql = "";
		StringBuilder whereSql = new StringBuilder();
		
		if(StringUtils.isNotEmpty(startTime)) {
			whereSql.append(" and cdate >= '"+startTime+"' ");
		}
		if(StringUtils.isNotEmpty(endTime)) {
			whereSql.append(" and cdate <= '"+endTime+"' ");
		}
		if(StringUtils.isNotEmpty(product_id)) {
			if("-1".equals(product_id)) {
				whereSql.append(" and product_id in (1,-1) "); //由于车主无忧产品 可能是-1或者1
			} else {
				whereSql.append(" and product_id = "+Integer.valueOf(product_id)+" ");
			}
		}
		if(StringUtils.isNotEmpty(channel)) {
			whereSql.append(" and channel = "+Integer.valueOf(channel)+" ");
		}
		
		sql =  " select cdate,totalCount,successCount,faildCount,channel,product_id from phone_message_statistical where 1 = 1 ";
		sql +=   whereSql.toString();
		sql += " order by cdate desc ";
		List  dataList = baseDao.list(sql, PhoneMessageStatistical.class);
		
		if(null != dataList && dataList.size() > 0) {
			for(int i = 0; i < dataList.size(); i++) {
				Object object = dataList.get(i);
				if(object instanceof PhoneMessageStatistical) {
					PhoneMessageStatistical vo = (PhoneMessageStatistical)object;
					vo.setChannel_name(channelMap.get(vo.getChannel()));
					Integer productId = vo.getProduct_id();
					System.out.println(productId);
					if(productId == 1) {
						vo.setProduct_name("车主无忧");
					} else {
						BaseDao relaseDao = new BaseDao(Constant.POOL_LIFE);
						sql = "select DISTINCT name as product_name from comm_product_prdid where prdid = ? ";
						PhoneMessageStatistical tempVo = relaseDao.get(sql, PhoneMessageStatistical.class,productId);
						if(tempVo!=null)
							vo.setProduct_name(tempVo.getProduct_name());
					}
				}
			}
		}
		String value = exportCVS(dataList);
		input = new ByteArrayInputStream(value.getBytes("GBK"));
		fileName = System.currentTimeMillis() + ".csv";
		return ActionSupport.SUCCESS;
	}
	
	
	public String exportCVS(List<PhoneMessageStatistical> list) {
		StringBuilder builder = new StringBuilder();
		builder.append("日期,总数,发送成功数,发送失败数,短信提供商,产品名称\r\n");
		
		for (PhoneMessageStatistical vo : list) {
			
			builder.append(vo.getCdate()).append(","); 
			builder.append(vo.getTotalCount()).append(","); 
			builder.append(vo.getSuccessCount()).append(",");
			builder.append(vo.getFaildCount()).append(",");
			builder.append(vo.getChannel_name()).append(",");
			builder.append(vo.getProduct_name()).append(",");
			builder.append("\r\n");
		}
		return builder.toString();
	}
	
	
	
	
	
}
